#!/bin/sh
. /usr/share/libubox/jshn.sh
. /lib/functions.sh

get_json_data() {
    #通过ubus读取设备电源信息
    local res=$(ubus call sihan.energy info)
    
    json_init
    json_load "$res" &> /dev/null
    if [ "$?" != 0 ]; then
            return
    fi
    json_get_var equipmentTemperature equipmentTemperature
    json_get_var equipmentHumidity equipmentHumidity
    json_get_var batteryTemperature batteryTemperature
    json_get_var totalWorkingCurrent totalWorkingCurrent
    json_get_var batteryVoltage batteryVoltage
    json_get_var batteryLevel batteryLevel
    json_get_var chargingCurrent chargingCurrent
    json_get_var chargingVoltage chargingVoltage
    json_get_var runDay runDay
    json_get_var lowVolCnt lowVolCnt
    json_get_var todayDischarge todayDischarge
    json_get_var yesterdayDischarge yesterdayDischarge
    json_get_var totalDischarge totalDischarge
    json_get_var todayCharge todayCharge
    json_get_var yesterdayCharge yesterdayCharge
    json_get_var totalCharge json_get_var
    #通过ubus读取设备cpu/内存等信息
    local res2=$(ubus call system info)

    #组装json数据
    json_init

    json_add_string "equipmentType" "02"
    json_add_string "equipmentNumber" ""
    json_add_object "basicData"
    json_add_string "model" ""
    json_add_string "softwareVersion" ""
    json_add_string "ip" "192.168.2.40"
    json_add_string "gatewayIp" "192.168.2.1"
    json_add_string "netmask" "255.255.255.0"
    json_add_string "locaMacAddress" "54:ef:33:47:01:ed"
    json_add_string "preferredDnsIp" ""
    json_add_string "alternateDnsIp" ""
    json_select ..
    json_add_object "statusData"

    json_add_string "cpuUsage" "0.1"
    json_add_string "memoryUsage" "0.27"
    json_add_string "networkPortFlow" ""
    json_add_string "deviceCurrentTime" ""
    json_select ..
    json_add_object "powerSupplyStatusData"
    json_add_string "equipmentTemperature" "$equipmentTemperature"
    json_add_string "equipmentHumidity" "$equipmentHumidity"
    json_add_string "batteryTemperature" "$batteryTemperature"
    json_add_string "totalWorkingCurrent" "$totalWorkingCurrent"
    json_add_string "batteryVoltage" "$batteryVoltage"
    json_add_string "batteryLevel" "$batteryLevel"
    json_add_string "chargingCurrent" "$chargingCurrent"
    json_add_string "chargingVoltage" "$chargingVoltage"
    json_select ..

}

foreach_server() {
    config_get enable $1 enable
    if $enable; then
        config_get server_ip $1 host
        config_get server_port $1 port
        config_get username $1 username
        config_get password $1 password
        config_get pubtopic $1 pubtopic

        mosquitto_pub -h $server_ip -p $server_port -m "$(json_dump)" -t $pubtopic -u $username -P $password
    fi
}

excu_send_iot()
{
    config_load idc_config
    config_get sn common sn
    get_json_data
    json_add_string "equipmentNumber" "$sn"
    config_foreach foreach_server server
}

excu_send_iot